﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.IO.Compression;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint;
using HPT.Utilities;

namespace HPT
{
    /// <summary>
    /// Fix Ajax action for User Controls for Webpart
    /// </summary>
    public class OUserControl : UserControl
    {
        public void EnsureUpdatePanelFixups()
        {
            if (this.Page.Form != null)
            {
                string formOnSubmitAtt = this.Page.Form.Attributes["onsubmit"];
                if (formOnSubmitAtt == "return _spFormOnSubmitWrapper();")
                {
                    this.Page.Form.Attributes["onsubmit"] = "_spFormOnSubmitWrapper();";
                }
            }

            ScriptManager.RegisterStartupScript(Page, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "UpdatePanelFixupOUserControl", "_spOriginalFormAction = document.forms[0].action; _spSuppressFormOnSubmitWrapper=true;", true);
        }

        public bool IsSiteAdmin
        {
            get
            {
                if (OWeb.CurrentUser == null) 
                    return false;
                else
                    return OWeb.CurrentUser.IsSiteAdmin || OWeb.CurrentUser.Groups.Cast<SPGroup>().Any(g => g.Name.EndsWith("Owners"));
            }
        }

        public bool IsEditPermission
        {
            get
            {
                if (OWeb.CurrentUser == null)
                    return false;
                else
                    return OWeb.CurrentUser.Groups.Cast<SPGroup>().Any(g => g.Name.EndsWith("Members")) || IsSiteAdmin ;
            }
        }

        public string qsCategory
        {
            get
            {
                if (ViewState["_ct"] == null) ViewState["_ct"] = OConvert.ToString(Request.QueryString["_ct"]);
                return GetCategory((string)ViewState["_ct"]);
            }
            set { ViewState["_ct"] = value; }
        }

        public string GetCategory(string ct)
        {
            switch (ct)
            {
                case "kd": ct = "Kinh doanh"; break;
                case "cn": ct = "Công nghệ"; break;
                case "xna": ct = "Xóm nhiếp ảnh"; break;
                case "bpt": ct = "Ban phong trào"; break;
                case "tt": ct = "Thể thao"; break;
                case "st": ct = "Sáng tác"; break;
                case "cd": ct = "Chân dung"; break;
                case "cmc": ct = "Cười mỉm chi"; break;
                case "bcb": ct = "Bạn có biết"; break;
                default: ct = ct; break;
            }
            return ct;
        }

        public int qsID
        {
            get
            {
                if (ViewState["_id"] == null) ViewState["_id"] = OConvert.ToInt(Request.QueryString["_id"]);
                return (int)ViewState["_id"];
            }
            set { ViewState["_id"] = value; }
        }


        public bool IsDlg
        {
            get
            {
                return !String.IsNullOrEmpty(base.Request.QueryString["IsDlg"]);
            }
        }
        public void CommitPopup()
        {
            if (IsDlg) ScriptManager.RegisterStartupScript(this, this.GetType(), String.Format("CommitPopup_{0}", Guid.NewGuid()), "window.frameElement.commitPopup();", true);
        }
        public bool ClearCache
        {
            get
            {
                return !String.IsNullOrEmpty(base.Request.QueryString["Cls"]);
            }
        }
    }

    /// <summary>
    /// Move ViewState to File fix porblem large page return
    /// </summary>
    public class OLayoutsPageBase : UnsecuredLayoutsPageBase
    {
        public void EnsureUpdatePanelFixups()
        {
            if (this.Page.Form != null)
            {
                string formOnSubmitAtt = this.Page.Form.Attributes["onsubmit"];
                if (formOnSubmitAtt == "return _spFormOnSubmitWrapper();")
                {
                    this.Page.Form.Attributes["onsubmit"] = "_spFormOnSubmitWrapper();";
                }
            }

            ScriptManager.RegisterStartupScript(Page, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "UpdatePanelFixupOLayoutsPageBase", "_spOriginalFormAction = document.forms[0].action; _spSuppressFormOnSubmitWrapper=true;", true);
        }

        public OLayoutsPageBase()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        /// <summary>
        /// Saves any view-state and control-state information for the page.
        /// </summary>
        /// <param name="state">The state.</param>
        /// <remarks></remarks>
        protected override void SavePageStateToPersistenceMedium(object state)
        {
            try
            {
                LosFormatter los = new LosFormatter();
                StringWriter sw = new StringWriter();
                los.Serialize(sw, state);

                StreamWriter w = File.CreateText(ViewStateFilePath);
                w.Write(sw.ToString());
                w.Close();
                sw.Close();
            }
            catch(Exception ex)
            {
                SPUtility.TransferToErrorPage(String.Format("Try update permission for folder '{0}' to write data files. ErrorMSG: {1}", Constants.Paths.TempPath, ex.Message));
            }
        }

        /// <summary>
        /// Loads any saved view-state information to the <see cref="T:System.Web.UI.Page"/> object.
        /// </summary>
        /// <returns>The saved view state.</returns>
        /// <remarks></remarks>
        protected override object LoadPageStateFromPersistenceMedium()
        {
            // determine the file to access
            if (!File.Exists(ViewStateFilePath))
                return null;
            else
            {
                // open the file
                StreamReader sr = File.OpenText(ViewStateFilePath);
                string viewStateString = sr.ReadToEnd();
                sr.Close();

                // deserialize the string
                LosFormatter los = new LosFormatter();
                return los.Deserialize(viewStateString);
            }
        }


        /// <summary>
        /// Gets the view state file path.
        /// </summary>
        /// <remarks></remarks>
        public string ViewStateFilePath
        {

            get
            {
                string fileName = string.Empty;
                string filepath = string.Empty;
                HiddenField hfVSFileName = null;
                string VSFileName = "";

                try
                {
                    // Get the HiddenField Key from the page
                    hfVSFileName = FindControl(this, "hfVSFileName") as HiddenField;
                }
                catch { }

                // Get the HiddenField value from the page
                string hfVSFileNameVal = string.Empty;
                if(hfVSFileName != null) 
                    hfVSFileNameVal = GetValue(hfVSFileName.UniqueID.ToString());
                if (!string.IsNullOrEmpty(hfVSFileNameVal))
                {
                    VSFileName = hfVSFileNameVal;
                }

                if (!Page.IsPostBack)
                {
                    VSFileName = GenerateGUID();
                    hfVSFileName.Value = VSFileName;

                    //Removing files from Server
                    RemoveFilesfromServer();
                }

                fileName = VSFileName + "-" + Path.GetFileNameWithoutExtension(Request.Path).Replace("/", "-") + ".vs";
                filepath = Path.Combine(Constants.Paths.ViewState, fileName);

                return filepath;

            }
        }

        /// <summary>
        /// Finds the control.
        /// </summary>
        /// <param name="root">The root.</param>
        /// <param name="controlId">The control id.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static Control FindControl(Control root, string controlId)
        {
            if (root.ID == controlId)
            {
                return root;
            }

            foreach (Control c in root.Controls)
            {
                Control t = FindControl(c, controlId);
                if (t != null)
                {
                    return t;
                }
            }

            return null;
        }
        public string GetValue(string uniqueId)
        {
            return System.Web.HttpContext.Current.Request.Form[uniqueId];
        }

        /// <summary>
        /// Removes the filesfrom server.
        /// </summary>
        /// <remarks></remarks>
        private void RemoveFilesfromServer()
        {
            try
            {
                DirectoryInfo _Directory = new DirectoryInfo(Constants.Paths.ViewState);
                FileInfo[] files = _Directory.GetFiles();
                DateTime threshold = DateTime.Now.AddDays(-3);
                foreach (FileInfo file in files)
                {
                    if (file.CreationTime <= threshold)
                        file.Delete();
                }
            }
            catch (Exception ex)
            {
                SPUtility.TransferToErrorPage(String.Format("Try update permission for folder '{0}' to write data files. ErrorMSG: {1}", Constants.Paths.TempPath, ex.Message));
                //throw new ApplicationException("Removing Files from Server");
            }
        }
        /// <summary>
        /// A GUID is created to store the file names
        /// </summary>
        private string GenerateGUID()
        {
            return System.Guid.NewGuid().ToString("");
        }

        public int qsID
        {
            get
            {
                if (ViewState["_id"] == null) ViewState["_id"] = OConvert.ToInt(Request.QueryString["_id"]);
                return (int)ViewState["_id"];
            }
            set { ViewState["_id"] = value; }
        }
        public bool IsSiteAdmin { get { return OWeb.CurrentUser.IsSiteAdmin || OWeb.CurrentUser.Groups.Cast<SPGroup>().Any(g => g.Name.EndsWith("Owners")); } }
    }

}
